package algorithm.子数组达到规定累加和的最大长度系列问题;

public class LongestSumSubArrayLengthInPositiveArray {


    public static int getMaxLength(int[] arr, int K){
        int max = 0;
        int left = 0;//左边界
        int right = 0;//表示右边界的下一个位置
        int value = 0;
        while(left < arr.length){//右指针到达了最右边时，左指针还需要继续判断
            if((value < K || right == left) && right < arr.length){
                value += arr[right++];//需要注意当左右指针相遇时要右移右指针
            } else if(value == K){
                max = Math.max(max, right - left);
                if(right < arr.length)
                    value += arr[right++];
                else
                    break;
            } else {
                value -= arr[left++];
            }

        }
        return max;
    }

    // for test
    public static int right(int[] arr, int K) {
        int max = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i; j < arr.length; j++) {
                if (valid(arr, i, j, K)) {
                    max = Math.max(max, j - i + 1);
                }
            }
        }
        return max;
    }

    // for test
    public static boolean valid(int[] arr, int L, int R, int K) {
        int sum = 0;
        for (int i = L; i <= R; i++) {
            sum += arr[i];
        }
        return sum == K;
    }

    // for test
    public static int[] generatePositiveArray(int size, int value) {
        int[] ans = new int[size];
        for (int i = 0; i != size; i++) {
            ans[i] = (int) (Math.random() * value) + 1;
        }
        return ans;
    }

    // for test
    public static void printArray(int[] arr) {
        for (int i = 0; i != arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int len = 50;
        int value = 100;
        int testTime = 500000;
        System.out.println("test begin");
        for (int i = 0; i < testTime; i++) {
            int[] arr = generatePositiveArray(len, value);
            int K = (int) (Math.random() * value) + 1;
            int ans1 = getMaxLength(arr, K);
            int ans2 = right(arr, K);
            if (ans1 != ans2) {
                System.out.println("Oops!");
                printArray(arr);
                System.out.println("K : " + K);
                System.out.println(ans1);
                System.out.println(ans2);
                break;
            }
        }
        System.out.println("test end");
    }

}
